In object-oriented programming, inappropriately accessing static members of a base class via derived types is considered a code smell.
Static members are associated with the class itself, not with any specific instance of the class or its children classes. Accessing through the
wrong type suggests a misunderstanding of the ownership and role of this member. This can make the maintenance of the code more complicated.
Therefore, the access should be done directly through the base class to maintain clarity and avoid potential misunderstandings.
Exceptions
This rule doesn’t raise an issue for constants. If the variable is const
, there is no risk of confusion.
Noncompliant code example
class Parent {
public:
static int count;
};
class Child : public Parent {
public:
Child() {
Child::count++; // Noncompliant
}
};
Compliant solution
class Parent {
public:
static int count;
};
class Child : public Parent {
public:
Child() {
Parent::count++;
}
};